package com.hslxy.niukewang.controller;

import com.google.code.kaptcha.Producer;
import com.hslxy.niukewang.dao.LoginTicketMapper;
import com.hslxy.niukewang.entity.User;
import com.hslxy.niukewang.service.UserService;
import com.hslxy.niukewang.util.CommunityUtil;
import com.hslxy.niukewang.util.Constant;
import com.hslxy.niukewang.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements Constant {
    @Autowired
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private Producer kaptchaProducer;

    @Value("${server.servlet.context-path}")
    private String CONTEXT_PATH;

    @Autowired
    private RedisTemplate redisTemplate;



    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String getRegisterPage(){
        return "/site/register";
    }

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLoginPage(){
        return "/site/login";
    }

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public String register(Model model, User user){
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()){
            model.addAttribute("msg", "注册成功, 我们已经向您的邮箱发送了一封邮件，请尽快激活");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("emailMsg", map.get("emailMsg"));
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/register";
        }
    }

//    激活邮件处理
    @RequestMapping(path = "/activation/{id}/{code}", method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("id") int id, @PathVariable("code") String code){
//        http://localhost:8080/niukewang/activation/152/e18aa8a6c84a436da6509542b5663d60
        int activation = userService.activation(id, code);
        switch (activation){
            case ACTIVATION_SUCCESS:
                model.addAttribute("msg", "激活成功");
                model.addAttribute("target", "/login");
                break;
            case ACTIVATION_FAILURE:
                model.addAttribute("msg", "激活失败,激活码错误");
                model.addAttribute("target", "/index");
                break;
            case ACTIVATION_REPEAT:
                model.addAttribute("msg", "重复激活");
                model.addAttribute("target", "/index");
                break;
        }
        return "/site/operate-result";
    }

//    生成二维码
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/){
//        生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
//        验证码存入session
//        session.setAttribute("kaptcha", text);
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(CONTEXT_PATH);
        response.addCookie(cookie);
//        将验证码存入redis
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(kaptchaKey, text, 60, TimeUnit.SECONDS);

        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            logger.error("生成失败", e);
        }

    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String postLogin(String username, String password, String code, boolean rememberme,
                            Model model, /*HttpSession session,*/ HttpServletResponse response, @CookieValue("kaptchaOwner") String kaptchaOwner){
//        String kaptcha = (String)session.getAttribute("kaptcha");
//        从redis中取验证码
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)){
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }
        if(StringUtils.isBlank(code) || StringUtils.isBlank(kaptcha) || !code.equalsIgnoreCase(kaptcha)){
            model.addAttribute("codeMsg", "验证码错误");
            return "/site/login";
        }
        int expiredSeconds = rememberme?REMEMBER_EXPIRED_SECONDS:DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            //        创建一个cookie
            Cookie cookie = new Cookie("ticket", (String) map.get("ticket"));
//        设置生存时间
            cookie.setMaxAge(expiredSeconds);
            cookie.setPath(CONTEXT_PATH);
//        设置cookie
            response.addCookie(cookie);
            return "redirect:/index";
        }else{
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }
    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }
}
